package org.xxpay.pay.channel.maicheng;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.springframework.stereotype.Component;
import org.xxpay.common.http.HttpRequestTemplate;
import org.xxpay.common.util.sign.SignUtils;
import org.xxpay.common.util.str.StringUtils;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.entity.TransOrder;
import org.xxpay.pay.channel.BaseTrans;

import java.util.Map;

@Component
public class MaichengTransService extends BaseTrans {
    private final static String logPrefix = "【麦橙】";

    @Override
    public String getChannelName() {
        return MaichengConfig.CHANNEL_NAME;
    }

    @Override
    public JSONObject balance(String payParam) {
        JSONObject retObj = buildRetObj();
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, "没有余额查询接口");
        return retObj;
    }

    /**
     * 代付订单
     *
     * @param transOrder
     * @return
     */
    @Override
    public JSONObject trans(TransOrder transOrder) {
        JSONObject retObj = buildRetObj();
        MaichengConfig config = new MaichengConfig(getTransParam(transOrder));
        Map<String,Object> params = Maps.newHashMap();
        //设置请求参数
        setParams(transOrder, config, params);
        _log.info("{}申请代付请求参数：{}", logPrefix, params.toString());
        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(null);
        JSONObject origin = requestTemplate.postForObject(config.getRequestUrl()+MaichengConfig.REQ_TRANS_URL_FIXX, params, JSONObject.class);
        retObj.put("isSuccess", false);
        retObj.put("transOrderId", transOrder.getTransOrderId());
        if(StringUtils.equals(origin.getString("code"),"0000")){
            JSONObject data = JSONObject.parseObject(origin.getString("data"));
            retObj.put("channelOrderNo", data.getString("merchantWithdrawNo"));
            retObj.put("isSuccess", true);
            // 1. 处理中 2. 成功 3. 失败
            if(StringUtils.equals(origin.getString("withdrawStatus"),"3")) {
                retObj.put("status", 1);
            }else if(StringUtils.equals(origin.getString("withdrawStatus"),"1")){
                retObj.put("status", 2);
            }else{
                retObj.put("status", 3);
            }
            return retObj;
        }
        // 1. 处理中 2. 成功 3. 失败
        retObj.put("status", 3);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, "下单失败[" + origin.getString("message") + "]");
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        return retObj;
    }

    /**
     * 订单查询接口
     *
     * @param transOrder
     * @return
     */
    @Override
    public JSONObject query(TransOrder transOrder) {
        MaichengConfig config = new MaichengConfig(getTransParam(transOrder));
        String payOrderId = transOrder.getTransOrderId();
        _log.info("{}开始查询代付通道订单,payOrderId={}", logPrefix, payOrderId);
        Map<String, Object> params = Maps.newHashMap();
        params.put("merchantId", config.getAppId());
        params.put("merchantWithdrawNo", transOrder.getTransOrderId());
        params.put("sign", getSign(params, config.getPublicKey()));
        _log.info("{}代付查询请求参数：{}", logPrefix, params.toString());
        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(null);
        JSONObject origin = requestTemplate.postForObject(config.getRequestUrl()+MaichengConfig.REQ_TRANS_QUERY_URL_FIXX, params, JSONObject.class);
        _log.info("{}代付查询响应参数：{}", logPrefix, origin.toJSONString());
        JSONObject retObj = buildRetObj();
        if(StringUtils.equals(origin.getString("code"),"0000")){
            JSONObject data = JSONObject.parseObject(origin.getString("data"));
            retObj.put("isSuccess", true);
            retObj.put("transOrderId", transOrder.getTransOrderId());
            retObj.putAll(origin);
            String status = data.getString("withdrawStatus");
            if (StringUtils.equals(status,"1")) {
                retObj.put("status", 2); // 2表示成功
            } else if (StringUtils.equals(status,"0")) {
                retObj.put("status", 1); // 3表示失败
            } else {
                retObj.put("status", 3); // 1处理中
            }
            retObj.put("channelOrderNo", origin.getString("withdrawNo"));
            retObj.put("channelObj", origin);
            return retObj;
        }
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, origin.getString("message"));
        retObj.put("channelErrCode", origin.getString("code"));
        retObj.put("isSuccess", false);
        return retObj;
    }

    //设置请求参数
    private void setParams(TransOrder transOrder,MaichengConfig config,Map<String,Object> params){

        params.put("merchantId", config.getAppId());
        params.put("merchantWithdrawNo", transOrder.getMchTransNo());
        params.put("amt", AmountUtil.convertCent2Dollar(String.valueOf(transOrder.getAmount())));
        params.put("bankNo", transOrder.getAccountNo());
        params.put("acctName", transOrder.getAccountName());
        params.put("sign", getSign(params, config.getPrivateKey()));

    }

    //获取sign
    private String getSign(Map<String,Object> params, String key){
        String signTxt = SignUtils.parameterText(params);
        _log.info("{}待签名字符串：{}", logPrefix, signTxt+"&key="+key);
        String sign = SignUtils.MD5.createSign(signTxt, "&key="+key, SignUtils.CHARSET_UTF8).toUpperCase();
        return sign;
    }
}
